import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import './MenuBar.css';

const defaultMenu = [
  { key: '/dashboard', label: '仪表盘', icon: '📊' },
  { key: '/work', label: '工作台', icon: '🛠️' },
  { key: '/analysis', label: '分析页', icon: '📈' },
  { key: '/ecommerce', label: '电子商务', icon: '🛒' },
  { key: '/system', label: '系统管理', icon: '⚙️', children: [
    { key: '/system/users', label: '用户管理', icon: '👤' },
    { key: '/system/menus', label: '菜单管理', icon: '📋' }
  ] },
  { key: '/content/manage', label: '内容管理', icon: '📝' }
];

const MenuBar = ({ onSelect, selectedKey }) => {
  const location = useLocation();
  const [menus, setMenus] = useState(defaultMenu);
  const [openKeys, setOpenKeys] = useState([]);

  useEffect(() => {
    // 可扩展为后端获取菜单
    setMenus(defaultMenu);
  }, []);

  const handleSelect = (item) => {
    if (onSelect) onSelect(item);
  };

  const handleToggle = (key) => {
    setOpenKeys(keys => keys.includes(key) ? keys.filter(k => k !== key) : [...keys, key]);
  };

  // 递归渲染菜单
  const renderMenus = (items, level = 0) => (
    <ul className={`menu-bar-list${level > 0 ? ' submenu-list' : ''}`}
        style={{ paddingLeft: level ? 16 : 0 }}>
      {items.map(item => {
        const hasChildren = item.children && item.children.length > 0;
        const isOpen = openKeys.includes(item.key);
        const isActive = selectedKey === item.key;
        return (
          <li
            key={item.key}
            className={`menu-bar-item${isActive ? ' active' : ''}${hasChildren ? ' has-children' : ''}`}
            style={level > 0 ? { background: '#f3f6fd' } : {}}
          >
            <div
              className="menu-bar-item-inner"
              onClick={() => hasChildren ? handleToggle(item.key) : handleSelect(item)}
              style={{ paddingLeft: 8 + level * 18, display: 'flex', alignItems: 'center', cursor: 'pointer' }}
            >
              <span className="menu-bar-icon">{item.icon}</span>
              <span className="menu-bar-label">{item.label}</span>
              {hasChildren && (
                <span className={`menu-bar-arrow${isOpen ? ' open' : ''}`}>{isOpen ? '▼' : '▶'}</span>
              )}
            </div>
            {hasChildren && isOpen && renderMenus(item.children, level + 1)}
          </li>
        );
      })}
    </ul>
  );

  return (
    <nav className="menu-bar-container">
      <div className="menu-bar-logo">AI Demo</div>
      {renderMenus(menus)}
    </nav>
  );
};

export default MenuBar; 